#include <rthw.h>
#include <rtthread.h>
#include <stdio.h>
#include <ctype.h>
#include "GPIB.h"
#include "network\tcpserver.h"
#include "string.h"
#include "emac.h"
#include "rtc.h"
#include "IAP\IAP.h"
#include "led.h"
#include <stdlib.h>

#ifdef RT_USING_DFS
#include <dfs.h>
#include <dfs_posix.h>
#include <sd.h>
//#include <dfs_init.h>
#include <dfs_fs.h>
#include <dfs_elm.h>
#endif
#include <dfs_posix.h> 

static rt_uint8_t compile_date[]=__DATE__;
static rt_uint8_t compile_time[]=__TIME__;

static rt_uint32_t now_ms=0,last_ms=0;

rt_uint8_t DIO[8]={25,19,21,23,26,18,20,22}; //DIO1,DIO5

rt_uint8_t rx_state=0;				// Rx state machine state
rt_uint8_t tx_state=0;				// Tx state machine state



//static rt_uint8_t gpib_address=0;
static rt_uint8_t source_device=0;
//static rt_uint8_t com_device[32][2]={0};									//com_device[0][0]是否使用,com_device[0][1](数据来源|协议类型)
//static rt_uint8_t current_gpib_address=0; 								//当前GPIB


static char offline_filename[16];
static rt_uint8_t offline_GPIB_PORT=0;

static char timestr[GPIB_MAX_RX_LEN+128],tempstr[10];
static char t[256]; 
	

char  *care_str[] =
{
	"care",
	"1.50",
	"USB_NET_2_GPIB",
	"DS18B20",
	"DHT22",
	"rt-thread",
};
 

char 	*set_file[] = 
{
	"/setting.txt",
	"/save.txt",
};

char  *gpib_no_return[] =
{
//   "INSTR",
  "INIT",
  "*TRG",
 	"*CLS",
	"*RCL",
	"*RST",
	"*SAV",
	"*TST?",//自检
	"ABOR",//停止
// 	" ",
	"*SRE ",													//*SRE <enable value> 			 	*SRE?有返回
	"*ESE ",													//*ESE <enable value>        	*ESE?有返回	
	":ENABle ",//"STATus:QUEStionable:ENABle ",		//STATus:QUEStionable:ENABle?有返回
	"*PSC ",												//*PSC {0|1}									*PSC?有返回	
	":DEL ",//"TRIG:DEL ",
	":NPLC ",//"VOLT:DC:NPLC ",
	"TRIG:SOUR BUS",
	"TRIG:SOUR IMM",
	":AUTO ",//"TRIG:DEL:AUTO ", //on off
	":ENAB ",//"STAT:OPER:ENAB ",
	"CONF:",
	//"CONF:RES",
	//"CONF:FRES",
	//"CONF:VOLT",
	":APER ",//"PER:APER ",
	":RANG ",//"FREQ:VOLT:RANG ",
	":RES ",//"FRES:RES ",//"RES:RES "
//	":MEM",
	"DISP:",		//以下追加 2019-11-29 by ZDD
	"DISP ",
	":STAT ",
	":CODE ",
	":STR ",
	":COUN ",
};



rt_bool_t NRFD_IS_HIGH()   	{TE_HIGH();		LPC_GPIO0->FIODIR &= ~BV(NRFD);		return PIN0_IS_SET(NRFD);}
rt_bool_t NDAC_IS_HIGH()   	{TE_HIGH();		LPC_GPIO0->FIODIR &= ~BV(NDAC);		return PIN0_IS_SET(NDAC);}
rt_bool_t ATN_IS_HIGH()   	{DC_HIGH();		LPC_GPIO1->FIODIR &= ~BV(ATN);		return PIN1_IS_SET(ATN);}
rt_bool_t SRQ_IS_HIGH()   	{DC_LOW();		LPC_GPIO1->FIODIR &= ~BV(SRQ);		return PIN1_IS_SET(SRQ);}
rt_bool_t EOI_IS_HIGH()   	{ATN_HIGH();	LPC_GPIO1->FIODIR &= ~BV(EOI);		return PIN1_IS_SET(EOI);}				///////待定
rt_bool_t DAV_IS_HIGH()   	{TE_LOW();		LPC_GPIO1->FIODIR &= ~BV(DAV);		return PIN1_IS_SET(DAV);}
rt_bool_t REN_IS_HIGH()   	{DC_HIGH();		LPC_GPIO2->FIODIR &= ~BV(REN);		return PIN2_IS_SET(REN);}
rt_bool_t IFC_IS_HIGH()   	{DC_HIGH();		LPC_GPIO2->FIODIR &= ~BV(IFC);		return PIN2_IS_SET(IFC);}




rt_uint8_t strnicmp (const char * str1, const char * str2, rt_uint8_t n)
{
rt_uint8_t i;
	for(i=0;i<n;i++)
	{
		if (toupper(str1[i]) != str2[i]) {break;}
	}	
	if (i==n) return 0; else return 1;
}

void care_GPIB_init(void)
{
	//75160 75162控制线
	LPC_GPIO0->FIODIR  |=  BV(PE);	
	LPC_GPIO1->FIODIR  |=  BV(TE)|BV(DC);	
	LPC_GPIO2->FIODIR  |=  BV(SC);
	
	//GPIB数据线
	LPC_GPIO1->FIODIR  &=  ~BV(DIO2)|BV(DIO3)|BV(DIO4)|BV(DIO6)|BV(DIO7)|BV(DIO8);		
	LPC_GPIO3->FIODIR  &=  ~BV(DIO1)|BV(DIO5);
	
	//GPIB信号控制线
	LPC_GPIO0->FIODIR  &=  ~BV(NRFD)|BV(NDAC); 
	LPC_GPIO1->FIODIR  &=  ~BV(DAV)|BV(ATN)|BV(DAV)|BV(EOI);		
	LPC_GPIO2->FIODIR  &=  ~BV(REN)|BV(IFC);

	ATN_HIGH();
	DAV_HIGH();

// 	gpib_ifc();
	EOI_LOW();
}


rt_uint8_t care_protocol_state(void)
{
	return !(protocol_state&0x01);
}




//device 	uart0------0;
//				uart1------1 (wifi);
//				NET--------2;
//				离线采集---4;



rt_uint8_t care_protocol(rt_uint8_t device, char *bytes, rt_uint8_t length)
{
	rt_uint8_t len;
	rt_uint32_t i,j;
	rt_uint8_t k;
	char no_return_flag;
	rt_uint8_t gpib_str_state=1,rly_state=0,addr_state=0;
//	rt_uint16_t t1;
//	rt_base_t level;
	
	if (protocol_state == 0)
	{
		protocol_state = 1;
		memset(t,0,256);
		while ((gpib_str_state != 0))
		{
			switch(gpib_str_state)
			{
				case 0x01:																			//整理字符串
					source_device = device;												//数据来源设备
					if (bytes[0] != 0x08)
					{	
						for(i=0;i<length-1;i++)
						{
								if ((bytes[i] < 0x20)||(bytes[i] > 0x7E)) //可见字符
								{
									gpib_str_state = 0;
									break;
								}
						}
						if((length > 1))//结尾只保留0x0A
						{
							if (bytes[strlen(bytes)-1] == ';') 		bytes[strlen(bytes)-1] 	= 0x00;
							if (bytes[strlen(bytes)-1] != 0x0A) 	bytes[strlen(bytes)] 		= 0x0A;
							if (bytes[strlen(bytes)-2] == 0x0D)		{bytes[strlen(bytes)-2] = 0x0A;bytes[strlen(bytes)-1] = 0x00;}
							length = strlen(bytes);
						}
					}
					if (length>1) 
						gpib_str_state = 2; 
					else 
						gpib_str_state = 0;//空指令过滤
					break;
				case 0x02:																			//08 16 07 AA 00 31 32 33 34 35
					switch ((unsigned char)bytes[3])
					{
						case 0xAA:gpib_str_state = 0x05;	no_return_flag = 0; break;	//发送地址bytes[1]GPIB仪表无返回指令
						case 0xAB:gpib_str_state = 0x05;	no_return_flag = 1;	break;				
						case 0xA0:gpib_str_state = 0x10; break;//设备参数查询	
						case 0xB0:gpib_str_state = 0x11; break;//设备参数设置			
						
						case 0xAE:gpib_str_state = 0x40; break;//温湿度查询						//20200105 08 16 07 AE 01(01-06) AE后跟传感器序号 00默认5，兼容原来指令和传感器
						case 0xAF:gpib_str_state = 0x09; gpib_address = bytes[1]&0x1F; break;	//20200105 读取bytes[1]GPIB仪表采集数据
						
						case 0xB1:gpib_str_state = 0x99; break;//重启设备	
						
						case 0xCA:gpib_str_state = 0x60; break;//读取自动采集配置
						case 0xCB:gpib_str_state = 0x70; break;//设置自动采集配置						
						case 0xCC:gpib_str_state = 0x80; break;//读取自动采集数据
						case 0xDD:gpib_str_state = 0x90; break;//模拟采集
						
						case 0xAC:gpib_str_state = 0x92; break;//设置SCPI等待时间
						case 0xAD:gpib_str_state = 0x93; break;//查询SCPI等待时间
						default:	if (bytes[0] != 0x08) gpib_str_state = 0x06; else gpib_str_state = 0x00; break;//透明传输GPIB									
					}
					break;					
				case 0x05:	//usb协议												//08 16 07 AA 00 31 32 33 34 35
					source_device = device|0x80;							//USB协议标识符，最后结果按照USB协议返回
					gpib_address = (bytes[1]&0x1F);	
					length = bytes[2]-2;
					if (length!=0) bytes = bytes+5;
					gpib_str_state = 7;
					break;
				case 0x06:	//透明协议
					len = sizeof(gpib_no_return)/sizeof(char *);
					no_return_flag = 0;
					for(i=0;i<=len-1;i++)																				//搜索无返回命令
					{
						if (strstr(bytes, gpib_no_return[i]) != NULL) 
						{
							no_return_flag = 1;
							break;
						}
					}	
					gpib_str_state = 7;
					break;
				case 0x07:	
					if 			(strnicmp(bytes,"CARE?",5) 								== 0)  				gpib_str_state = 0x90;
					else if (strnicmp(bytes,"CARE_RLY:",9) 						== 0)					gpib_str_state = 0x91;	
					else if (strnicmp(bytes,"CARE_UART2:",11) 				== 0)					gpib_str_state = 0x94;	
					else if (strnicmp(bytes,"CARE_UART1:",11) 				== 0)					gpib_str_state = 0x95;	
					else if (strnicmp(bytes,"CARE_NULL:",10) 					== 0)					gpib_str_state = 0x96;
					else if (strnicmp(bytes,"CARE_RESET",10) 					== 0) 				gpib_str_state = 0x99;	
				
					else if (strnicmp(bytes,"CARE_TEMP?",10) 					== 0)					gpib_str_state = 0x40;//CARE_SENSOR设置的传感器数值
					else if (strnicmp(bytes,"CARE_TIME?",10) 					== 0) 				gpib_str_state = 0x41;
					else if (strnicmp(bytes,"CARE_IP?",8) 						== 0)					gpib_str_state = 0x42;//LAN IP
				
					else if (strnicmp(bytes,"CARE_OFFLINE:1",14) 			== 0)					gpib_str_state = 0x43;	
					else if (strnicmp(bytes,"CARE_OFFLINE:0",14) 			== 0)					gpib_str_state = 0x44;//离线采集启动开关
					else if (strnicmp(bytes,"CARE_LISTEN:1",13) 			== 0)					gpib_str_state = 0x45;	
					else if (strnicmp(bytes,"CARE_LISTEN:0",13) 			== 0)					gpib_str_state = 0x46;//Listen_Only_Mode
				
//					else if (strnicmp(bytes,"CARE_VOLT?",10) 					== 0) 				gpib_str_state = 0x47;
					else if (strnicmp(bytes,"CARE_ADDR:",10) 					== 0) 				gpib_str_state = 0x48;//设置透传地址
					else if (strnicmp(bytes,"CARE_AUTO:",10) 					== 0) 				gpib_str_state = 0x49;//设置自动模式

					//添加各传感器独立访问命令   2019-11-29 by ZDD
					else if (strnicmp(bytes,"CARE_TEMP1?",11) 				== 0)					gpib_str_state = 0x4A;//18B20_1
					else if (strnicmp(bytes,"CARE_TEMP2?",11) 				== 0)					gpib_str_state = 0x4B;//18B20_2
					else if (strnicmp(bytes,"CARE_TEMP3?",11) 				== 0)					gpib_str_state = 0x4C;//SHT20ÎÂ¶È
					else if (strnicmp(bytes,"CARE_HUMI?",10) 					== 0)					gpib_str_state = 0x4D;//SHT20Êª¶È
					else if (strnicmp(bytes,"CARE_TEMP4?",11) 				== 0)					gpib_str_state = 0x4E;//BMP180ÎÂ¶È
					else if (strnicmp(bytes,"CARE_PRES?",10) 					== 0)					gpib_str_state = 0x4F;//BMP180ÆøÑ¹
				
					else if (strnicmp(bytes,"CARE_SENSOR:",12) 				== 0)					gpib_str_state = 0x50;//设置传感器序号
					else if (strnicmp(bytes,"CARE_TIMEOUT:",13) 			== 0)					gpib_str_state = 0x51;
					else if (strnicmp(bytes,"CARE_TIMEOUT?",13) 			== 0)					gpib_str_state = 0x52;//设置查询超时等待
					else if (strnicmp(bytes,"CARE_DATETIME:",14) 			== 0)					gpib_str_state = 0x53;
					
					else if (strnicmp(bytes,"CARE_ADDR?",10) 					== 0) 				gpib_str_state = 0x58;//查询透传地址
				
					else if (strnicmp(bytes,"CARE_WIFI?",10) 					== 0) 				gpib_str_state = 0x5A;//查询WIFI模块状态
					else if (strnicmp(bytes,"CARE_WIFI_SET",13) 			== 0) 				gpib_str_state = 0x5B;//设置wifi
					else if (strnicmp(bytes,"CARE_WIFI_RST",13) 			== 0) 				gpib_str_state = 0x5C;//还原wifi出厂设置
					else if (strnicmp(bytes,"CARE_SSID:",10) 					== 0)					gpib_str_state = 0x5D;//ssid
					else if (strnicmp(bytes,"CARE_KEY:",9) 						== 0)					gpib_str_state = 0x5E;//WIFI_KEY
					else if (strnicmp(bytes,"CARE_WIFI_DMM:",14) 			== 0) 				gpib_str_state = 0x5F;//设置wifi连接远程仪表，默认0无远程仪表，支持域名解析

					else if (strnicmp(bytes,"CARE_READ",9) 						== 0) 				gpib_str_state = 0x97;//非自动模式下CARE读取仪表数据
					else if (strnicmp(bytes,"CARE_LOC",8) 						== 0) 				gpib_str_state = 0x12;//释放仪表到LOCAL状态
					else if (strnicmp(bytes,"CARE_INFO?",10) 					== 0) 				gpib_str_state = 0x20;//查询固件编译时间
					else if (rt_strstr(bytes,"CARE") 									!= RT_NULL) 	gpib_str_state = 0x00;//错误指令
					else if (rt_strstr(bytes,"+OK") 									!= RT_NULL) 	gpib_str_state = 0x00;//错误指令
					
					else if((CARE_WIFI_MODE == 1)&&(gpib_address == 31)) gpib_str_state = 0x13;
					else gpib_str_state = 0x08;
					break;
//////////////////////////////////////////////////////////////////////////////////////////////						
//////////////////////////////////////////////////////////////////////////////////////////////						
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////	
				case 0x96:																									//CARE_NULL: 无返回命令  CARE_NULL:*CLS:23
					strcpy(bytes, bytes+10);
					if(strchr(bytes,':')!=NULL)
					{	
						len = strchr(bytes,':')-bytes;
						if ((bytes[len+1]>=0x30)&&(bytes[len+1]<=0x39))					//CARE_NULL:DISP:TEXT "10.000000V" 第二个冒号后判断是否是地址
						{
							strncpy(t,strchr(bytes,':')+1,2);
							gpib_address = atoi(t);
							bytes[len] = 0x0A;
							bytes[len+1] = 0x00;
						}
					}
				  length = strlen(bytes);//length-10;
					no_return_flag = 1;
					offline_return = 0x00;
					gpib_str_state = 0x08;
					break;	
				case 0x97:																									//GPIB是否返回仪器数据
					if (strnicmp(bytes,"CARE_READ:",10)==0)										//CARE_READ:22
           {
							strncpy(t,bytes+10,2);
							gpib_address = atoi(t);
           }
					gpib_str_state = 9;					
					break;
				case 0x13:	
						if(bytes[length-1]!=0x0A)
						{
								if(bytes[length-2]!=0x0D){bytes[length]=0x0D;bytes[length+1]=0x0A;length += 2;}
								else {bytes[length]=0x0A;length += 1;}
						}
						else
						{
								if(bytes[length-2]!=0x0D){bytes[length-1]=0x0D;bytes[length]=0x0A;length += 1;}
						}
						rt_device_write(rt_device_find("uart1"), 0, bytes, length);
						gpib_str_state = 0;					
						break;
					
				case 0x08:																									//GPIB寻址
					REN_LOW();	
					address_target_listen(gpib_address); 											//put instrument in listen
					gpib_write(bytes,length,1);	
					if (!no_return_flag) 
					{
						for(i=0;i<GPIB_WAIT_TIME;i++)
						{
							j = 2;
							while(j>0) j--;
						}
						if(care_auto)gpib_str_state = 9;else gpib_str_state = 0;
					} 
					else
					{
//						t[0]= 0x00;
//						return_care(bytes,t,1);																	//无返回命令时候CARE返回
						gpib_str_state = 0;
					}
					break;
				case 0x09:																									//GPIB是否返回仪器数据
					address_target_talk(gpib_address);												//put instrument in talk	
					gpib_read(1,1,0,0);
					gpib_str_state = 0;					
					break;
//////////////////////////////////////////////////////////////////////////////////////////////				
//////////////////////////////////////////////////////////////////////////////////////////////					
//////////////////////////////////////////////////////////////////////////////////////////////					
//////////////////////////////////////////////////////////////////////////////////////////////					
				case 0x10:												//08 16 07 A0 00 31 32 33 34 35
					switch ((unsigned char)bytes[4])
					{
						case 0xD0:gpib_str_state = 0x20; break;//查询CARE编译日期
						case 0xD1:gpib_str_state = 0x21; break;//查询CARE信息 
						case 0xD2:gpib_str_state = 0x22; break;//查询设备版本
						case 0xD3:gpib_str_state = 0x23; break;//查询DHCP是否激活
						case 0xD4: 														 //查询CARE IP
						case 0xD5: 														 //查询CARE GW
						case 0xD6:gpib_str_state = 0x26; break;//查询CARE MSK
						case 0xD7:gpib_str_state = 0x27; break;//查询CARE TCP_PORT
						//case 0xD8:gpib_str_state = 0x28; break;//D8已经更改为还原默认参数
						case 0xD9:gpib_str_state = 0x29; break;//查询CARE当前时间
						case 0xDA:gpib_str_state = 0x2A; break;//查询温湿度传感器类型
						case 0xDB:gpib_str_state = 0x2B; break;//查询透明协议时各端口对应GPIB地址
						case 0xDC:gpib_str_state = 0x2C; break;//查询MAC地址						
						case 0xDD:gpib_str_state = 0x2D; break;//查询串口0波特率
						case 0xDE:gpib_str_state = 0x2E; break;//查询串口1波特率
						case 0xDF:gpib_str_state = 0x2F; break;//查询串口转发
						
						default:	gpib_str_state = 0;		 break;
					}
					break;			
				case 0x11:												//08 16 07 B0 00 31 32 33 34 35
					switch ((unsigned char)bytes[4])
					{
						case 0xD0:gpib_str_state = 0x30; break;//设置LISTEN ONLY模式
						case 0xD1:gpib_str_state = 0x31; break;//设置LISTEN ONLY模式
						
						case 0xD3:gpib_str_state = 0x33; break;//设置DHCP是否激活
						case 0xD4:gpib_str_state = 0x34; break;//设置CARE IP
						case 0xD5:gpib_str_state = 0x35; break;//设置CARE GW
						case 0xD6:gpib_str_state = 0x36; break;//设置CARE MSK
						case 0xD7:gpib_str_state = 0x37; break;//设置CARE TCP_PORT
						case 0xD8:gpib_str_state = 0x38; break;//care参数还原默认
						case 0xD9:gpib_str_state = 0x39; break;//设置CARE当前时间
//						case 0xDB:gpib_str_state = 0x3B; break;//设置透明协议时各端口对应GPIB地址
//						
//						case 0xDD:gpib_str_state = 0x3D; break;//设置串口0波特率
//						case 0xDE:gpib_str_state = 0x3E; break;//设置串口1波特率
						case 0xDF:gpib_str_state = 0x3F; break;//设置串口转发
						
//////////////0xE0-0xE9新增内容，20200105						
						case 0xE0:gpib_str_state = 0x60; break;//设置GPIB透传地址
						case 0xE1:gpib_str_state = 0x61; break;//设置离线采集
						case 0xE2:gpib_str_state = 0x62; break;//设置CARE自动模式
						case 0xE3:gpib_str_state = 0x63; break;//设置wifi
						case 0xE4:gpib_str_state = 0x64; break;//还原wifi出厂设置
						case 0xE5:gpib_str_state = 0x65; break;//设置WIFI SSID
						case 0xE6:gpib_str_state = 0x66; break;//设置WIFI KEY
						case 0xE7:gpib_str_state = 0x67; break;//释放仪表到LOCAL状态
						case 0xE8:gpib_str_state = 0x68; break;//设置wifi连接远程仪表，默认0无远程仪表，支持域名解析
						case 0xE9:gpib_str_state = 0x69; break;//查询WIFI IP地址

						default:	gpib_str_state = 0;		 break;
					}
					break;	
				case 0x12:																									//GPIB寻址
					REN_HIGH();																								//GPIB REN释放
					address_target_listen(gpib_address); 											//put instrument in listen
					gpib_str_state = 0;
					break;
				
				
				
				case 0x20:				//CARE 编译信息
					strcpy(t, (char*)compile_date);
					strcat(t, " ");
					strcat(t, (char*)compile_time);
					len = strlen((char*)t); 
					return_care(bytes,t,len);
					gpib_str_state = 0;
					break;					
				case 0x21:				//CARE 信息
					if((unsigned char)bytes[2]==0x02)
					{strcpy(t, care_str[0]);}
					else if(((unsigned char)bytes[2]==0x03)&&((unsigned char)bytes[5]<=0x05))
					{strcpy(t, care_str[bytes[5]]);}
					len = strlen((char*)t); 
					return_care(bytes,t,len);
					gpib_str_state = 0;
					break;
				case 0x22:				//CARE版本					
					strcpy(t, care_str[1]);
					len = strlen((char*)t); 				
					return_care(bytes,t,len);
					gpib_str_state = 0;
					break;
				case 0x23:				//DHCP
					t[0]= BOOL_DHCP&0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;
				case 0x26:				//care_find_ip
					care_find_ip();
					if ((unsigned char)bytes[4] == 0xD4) {t[3]=(IP_ADDR>>24)&0xFF;t[2]=(IP_ADDR>>16)&0xFF;t[1]=(IP_ADDR>>8)&0xFF;t[0]=(IP_ADDR)&0xFF;}
					if ((unsigned char)bytes[4] == 0xD5) {t[3]=(GW_ADDR>>24)&0xFF;t[2]=(GW_ADDR>>16)&0xFF;t[1]=(GW_ADDR>>8)&0xFF;t[0]=(GW_ADDR)&0xFF;}
					if ((unsigned char)bytes[4] == 0xD6) {t[3]=(MSK_ADDR>>24)&0xFF;t[2]=(MSK_ADDR>>16)&0xFF;t[1]=(MSK_ADDR>>8)&0xFF;t[0]=(MSK_ADDR)&0xFF;}
					return_care(bytes,t,4);	
					gpib_str_state = 0;
					break;
				case 0x42:				//care_find_ip
					care_find_ip();
					sprintf(t,"%d.%d.%d.%d\r\n",
					(int)((IP_ADDR)&0xFF),
					(int)((IP_ADDR>>8)&0xFF),
					(int)((IP_ADDR>>16)&0xFF),
					(int)((IP_ADDR>>24)&0xFF));
					return_care(bytes,t,strlen(t));	
					gpib_str_state = 0;
					break;
				case 0x27:				//TCP_PORT
					t[0]= (TCP_SERVER_PORT>>8)&0xFF;
					t[1]= TCP_SERVER_PORT;
					return_care(bytes,t,2);
					gpib_str_state = 0;
					break;
				case 0x28:				//暂时没用
					t[0]= (UDP_SERVER_PORT>>8)&0xFF;
					t[1]= UDP_SERVER_PORT;
					return_care(bytes,t,2);
					gpib_str_state = 0;
					break;				
				case 0x29:				//RTC
					sprintf(t,"%04d%02d%02d%02d%02d%02d",
					(LPC_RTC->YEAR),
					(LPC_RTC->MONTH),
					(LPC_RTC->DOM),
					(LPC_RTC->HOUR),
					(LPC_RTC->MIN),
					(LPC_RTC->SEC));
					return_care(bytes,t,strlen(t));					
					gpib_str_state = 0;
					break;
				case 0x2A:				//查询温湿度传感器类型
					strcpy(t, care_str[3]);
					len = strlen((char*)t); 				
					return_care(bytes,t,len);
					gpib_str_state = 0;
					break;
				case 0x2B:																		//查询透明协议时各端口对应GPIB地址
					t[0]= 23;
					return_care(bytes,t,3);
					gpib_str_state = 0;
					break;
				case 0x2C:																		//MAC地址
					care_find_ip();	
					t[0]= MAC_ADDR[0];
					t[1]= MAC_ADDR[1];
					t[2]= MAC_ADDR[2];	
					t[3]= MAC_ADDR[3];
					t[4]= MAC_ADDR[4];
					t[5]= MAC_ADDR[5];				
					return_care(bytes,t,6);
					gpib_str_state = 0;
					break;
				case 0x2D:																		//urat0 brt
					t[0]= 0;	
					t[1]= (UART0_BAUDRATE>>16)&0xFF;
					t[2]= (UART0_BAUDRATE>>8)&0xFF;
					t[3]= (UART0_BAUDRATE)&0xFF;
					return_care(bytes,t,4);
					gpib_str_state = 0;
					break;
				case 0x2E:																		//urat1 brt
					t[0]= 0;	
					t[1]= (UART1_BAUDRATE>>16)&0xFF;
					t[2]= (UART1_BAUDRATE>>8)&0xFF;
					t[3]= (UART1_BAUDRATE)&0xFF;
					return_care(bytes,t,4);
					gpib_str_state = 0;
					break;
				case 0x2F:																		//urat1 brt
					t[0]= UART_Auto_Mode&0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;
				
				
				case 0x30:																		//启动LISTEN
					Listen_Only_Mode = 1;
					t[0]= Listen_Only_Mode&0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;
				case 0x31:																		//停止LISTEN
					Listen_Only_Mode = 0;
					t[0]= Listen_Only_Mode&0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;
			
				case 0x33://08 16 03 B0 D3 01									//设置DHCP
					BOOL_DHCP = bytes[5]&0x01;
					WriteFlash(0);				
					t[0] = 0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;			
				case 0x34://08 16 06 B0 D4 FF FF FF FF				//设置IP
					RT_LWIP_IPADDR0 = bytes[5];
					RT_LWIP_IPADDR1 = bytes[6];
					RT_LWIP_IPADDR2 = bytes[7];
					RT_LWIP_IPADDR3 = bytes[8];
					WriteFlash(0);				
					t[0] = 0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;				
				case 0x35://08 16 06 B0 D5 FF FF FF FF				//设置GW
					RT_LWIP_GWADDR0 = bytes[5];
					RT_LWIP_GWADDR1 = bytes[6];
					RT_LWIP_GWADDR2 = bytes[7];
					RT_LWIP_GWADDR3 = bytes[8];
					WriteFlash(0);				
					t[0] = 0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;		
				case 0x36://08 16 06 B0 D6 FF FF FF FF				//设置MSK
					RT_LWIP_MSKADDR0 = bytes[5];
					RT_LWIP_MSKADDR1 = bytes[6];
					RT_LWIP_MSKADDR2 = bytes[7];
					RT_LWIP_MSKADDR3 = bytes[8];
					WriteFlash(0);				
					t[0] = 0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;		
				case 0x37://08 16 04 B0 D7 FF FF							//设置TCP_PORT
					TCP_SERVER_PORT = (bytes[5]<<8) + bytes[6];
					WriteFlash(0);				
					t[0] = 0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;		
				case 0x38://08 100 02 B0 D8							     //CARE参数还原默认
					WriteFlash(1);				
					t[0] = 0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;			
				case 0x39://08 16 10 B0 D9 FF FF FF FF FF FF FF FF FF FF FF	FF FF FF		//设置CARE当前时间
					LPC_RTC->YEAR  = (bytes[5]-0x30)*1000 + (bytes[6]-0x30)*100 + (bytes[7]-0x30)*10 + (bytes[8]-0x30);
					LPC_RTC->MONTH = (bytes[9]-0x30)*10   + (bytes[10]-0x30);
					LPC_RTC->DOM   = (bytes[11]-0x30)*10 	+ (bytes[12]-0x30);
					LPC_RTC->HOUR  = (bytes[13]-0x30)*10 	+ (bytes[14]-0x30);
					LPC_RTC->MIN   = (bytes[15]-0x30)*10 	+ (bytes[16]-0x30);
					LPC_RTC->SEC   = (bytes[17]-0x30)*10 	+ (bytes[18]-0x30);
		
					t[0] = 0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;
				case 0x3B://08 16 05 B0 DB 17 17 17							//设置透明协议时各端口对应GPIB地址
					USB_GPIB_PORT  = bytes[5];
					WriteFlash(0);				
					t[0] = 0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;	
				
				case 0x3D://08 00 06 B0 DD 00 01 C2 00						//设置uart0波特率
					UART0_BAUDRATE = (bytes[6]<<16)+(bytes[7]<<8)+(bytes[8]);
					WriteFlash(0);				
					t[0] = 0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;	
				case 0x3E://08 00 06 B0 DE 00 01 C2 00						//设置uart1波特率
					UART1_BAUDRATE = (bytes[6]<<16)+(bytes[7]<<8)+(bytes[8]);
					WriteFlash(0);				
					t[0] = 0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;	
				case 0x3F://08 00 03 B0 DF 01									//设置uart1 uart0互相转发
					UART_Auto_Mode = bytes[5]&0x01;			
					t[0] = 0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;						
				case 0x40:				//08 00 02 AE 01(01-06) 
					if(bytes[4] == 00)SENSOR_INDEX = 5;
					else if(bytes[4] <= 0x06) SENSOR_INDEX = (bytes[4]-1);
					sprintf(t,"%.2f\r\n",SENSOR_DATA[SENSOR_INDEX]);
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				case 0x41:				//TIME?											
					sprintf(t,"%04d/%02d/%02d %02d:%02d:%02d.%03d\r\n",
					(LPC_RTC->YEAR),
					(LPC_RTC->MONTH),
					(LPC_RTC->DOM),
					(LPC_RTC->HOUR),
					(LPC_RTC->MIN),
					(LPC_RTC->SEC),
					ms_int);
					return_care(bytes,t,strlen(t));					
					gpib_str_state = 0;
					break;
				
				case 0x43:																		//启动CARE_OFFLINE
					offline_start = 1;
					gpib_str_state = 0;
					break;
				case 0x44:																		//停止CARE_OFFLINE
					offline_start = 0;
					gpib_str_state = 0;
					break;
				
				case 0x45:																		//启动LISTEN
					Listen_Only_Mode = 1;
					gpib_str_state = 0;
					break;
				case 0x46:																		//停止LISTEN
					Listen_Only_Mode = 0;
					gpib_str_state = 0;
					break;
				case 0x48:																		//address
					if			(strlen(bytes) == 13){addr_state = (bytes[10]-0x30)*10 + (bytes[11]-0x30);}
					else if	(strlen(bytes) == 12){addr_state = (bytes[10]-0x30);}
					
					gpib_address = addr_state&0x1F;
					
					sprintf(t,"SET_ADDR:%2d\r\n",gpib_address);
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				case 0x58:																		//address
					sprintf(t,"SET_ADDR:%2d\r\n",gpib_address);
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				case 0x49:																		//auto
					if	(strlen(bytes) == 12){care_auto = (bytes[10]-0x30);}	
					care_auto = care_auto&0x01;
					WriteFlash(0);
					sprintf(t,"SET_AUTO:%d\r\n",care_auto);
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				case 0x4A:				//CARE_TEMP1?  18B20_1
					sprintf(t,"%.2f\r\n",SENSOR_DATA[4]);
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				case 0x4B:				//CARE_TEMP2?  18B20_2	
					sprintf(t,"%.2f\r\n",SENSOR_DATA[5]);
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				case 0x4C:				//CARE_TEMP3?  SHT20温度
					sprintf(t,"%.2f\r\n",SENSOR_DATA[1]);
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				case 0x4D:				//CARE_HUMI?  SHT20湿度
					sprintf(t,"%.2f\r\n",SENSOR_DATA[0]);
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				case 0x4E:				//CARE_TEMP4?  BMP180温度
					sprintf(t,"%.2f\r\n",SENSOR_DATA[2]);
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				case 0x4F:				//CARE_PRES?  BMP180气压
					sprintf(t,"%.2f\r\n",SENSOR_DATA[3]);
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				case 0x50:																		//CARE_SENSOR:1
					if	(strlen(bytes) == 14){SENSOR_INDEX = (bytes[12]-0x30)&0x0F;}	
//					WriteFlash(0);
					sprintf(t,"SET_SENSOR:%d\r\n",SENSOR_INDEX);
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
					
				case 0x51://CARE_TIMEOUT:1500								//设置SCPI等待时间
					if					(strlen(bytes) == 19)GPIB_WAIT_TIME = (bytes[13]-0x30)*10000+(bytes[14]-0x30)*1000+(bytes[15]-0x30)*100+(bytes[16]-0x30)*10+(bytes[17]-0x30);
					else if			(strlen(bytes) == 18)GPIB_WAIT_TIME = (bytes[13]-0x30)*1000+(bytes[14]-0x30)*100+(bytes[15]-0x30)*10+(bytes[16]-0x30);
					else if			(strlen(bytes) == 17)GPIB_WAIT_TIME = (bytes[13]-0x30)*100+(bytes[14]-0x30)*10+(bytes[15]-0x30);
					else if			(strlen(bytes) == 16)GPIB_WAIT_TIME = (bytes[13]-0x30)*10+(bytes[14]-0x30);
					WriteFlash(0);				
					sprintf(t,"CARE_TIMEOUT:%d\r\n",GPIB_WAIT_TIME);
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;	
				case 0x52://CARE_TIMEOUT?													//查询SCPI等待时间(strstr(bytes, gpib_no_return[i])
					sprintf(t,"CARE_TIMEOUT:%d\r\n",GPIB_WAIT_TIME);
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				
				case 0x53://CARE_DATETIME:2019/12/27 14:59:00		//设置CARE当前时间
					if((bytes[18] == '/')&&(bytes[21] == '/')&&(bytes[24] == ' ')&&(bytes[27] == ':')&&(bytes[30] == ':'))
					{
						LPC_RTC->YEAR  = (bytes[14]-0x30)*1000 + (bytes[15]-0x30)*100 + (bytes[16]-0x30)*10 + (bytes[17]-0x30);
						LPC_RTC->MONTH = (bytes[19]-0x30)*10   + (bytes[20]-0x30);
						LPC_RTC->DOM   = (bytes[22]-0x30)*10 	+ (bytes[23]-0x30);
						LPC_RTC->HOUR  = (bytes[25]-0x30)*10 	+ (bytes[26]-0x30);
						LPC_RTC->MIN   = (bytes[28]-0x30)*10 	+ (bytes[29]-0x30);
						LPC_RTC->SEC   = (bytes[31]-0x30)*10 	+ (bytes[32]-0x30);
		
						sprintf(t,"CARE_DATETIME:%04d/%02d/%02d %02d:%02d:%02d\r\n",
						(LPC_RTC->YEAR),
						(LPC_RTC->MONTH),
						(LPC_RTC->DOM),
						(LPC_RTC->HOUR),
						(LPC_RTC->MIN),
						(LPC_RTC->SEC));
					
						return_care(bytes,t,strlen(t));				
					}						
					gpib_str_state = 0;
					break;
					
				case 0x5A://查询
					UART_Auto_Mode = 1;
					WIFI_TR1=0;
					gpib_str_state = 0;
					break;
				case 0x5B://设置
					if((strlen(CARE_KEY)!=0)&&(strlen(CARE_SSID)!=0))
					{
						UART_Auto_Mode = 1;
						WIFI_TR1=0x10;
					}
					else
					{
						strcpy(t,"SET WIFI ERROR!\r\n");
						return_care(bytes,t,strlen(t));
					}
					gpib_str_state = 0;
					break;
				case 0x5C://还原
					UART_Auto_Mode = 1;
					WIFI_TR1=0x20;
					gpib_str_state = 0;
					break;
				case 0x5D://CARE_SSID:		
					strcpy(CARE_SSID,(strstr(bytes, "CARE_SSID:")+10));
					if(CARE_SSID[strlen(CARE_SSID)-1] == 0x0A) CARE_SSID[strlen(CARE_SSID)-1] = 0x00;
					strcpy(t,"SET_SSID:");
					strcat(t,CARE_SSID);
					strcat(t,"\r\n");
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				case 0x5E://CARE_KEY:		
					strcpy(CARE_KEY,(strstr(bytes, "CARE_KEY:")+9));
					if(CARE_KEY[strlen(CARE_KEY)-1] == 0x0A) CARE_KEY[strlen(CARE_KEY)-1] = 0x00;
					strcpy(t,"SET_KEY:");
					strcat(t,CARE_KEY);
					strcat(t,"\r\n");
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				case 0x5F://CARE_WIFI_DMM:		
					strcpy(CARE_DMM,(strstr(bytes, "CARE_WIFI_DMM:")+14));
					if(CARE_DMM[strlen(CARE_DMM)-1] == 0x0A) CARE_DMM[strlen(CARE_DMM)-1] = 0x00;
					if(CARE_DMM[0] > 0x30) CARE_WIFI_MODE = 1;//CLIENT模式
					else if(CARE_DMM[0] == 0x30) CARE_WIFI_MODE = 0;//SERVER模式
					WriteFlash(0);
					strcpy(t,"CARE_DMM:");
					strcat(t,CARE_DMM);
					strcat(t,"\r\n");
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				
				case 0x90://08 00 02 DD 00							//模拟数据			
					sprintf(t,"+1.%08dE+01\r\n",(rt_uint8_t)(rt_tick_get()&0xFF));
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;	
				case 0x91://CARE_RLY:00
					if			(strlen(bytes) == 12){rly_state = (bytes[9]-0x30)*10 + (bytes[10]-0x30);}
					else if	(strlen(bytes) == 11){rly_state = (bytes[9]-0x30);}
					
					rly_state = rly_state&0x0F;
					PIN2_SET(GPIO_5);
					
					if(rly_state==0) 				PIN2_SET(GPIO_5); else PIN2_CLR(GPIO_5);
					if(rly_state>=0) rly_state=8-rly_state;		
					if((rly_state&0x04)==4) PIN0_SET(GPIO_6); else PIN0_CLR(GPIO_6);
					if((rly_state&0x02)==2) PIN0_SET(GPIO_7); else PIN0_CLR(GPIO_7);
					if((rly_state&0x01)==1) PIN0_SET(GPIO_8); else PIN0_CLR(GPIO_8);
				
					sprintf(t,"RLY_OPEN:0%d\r\n",(8-rly_state));
					return_care(bytes,t,strlen(t));
					gpib_str_state = 0;
					break;
				case 0x92://08 00 06 AC 00 00 00 00 01 								//设置SCPI等待时间
					GPIB_WAIT_TIME = (bytes[5]<<24)+(bytes[6]<<16)+(bytes[7]<<8)+(bytes[8]);
					WriteFlash(0);				
					t[0] = 0x01;
					return_care(bytes,t,1);
					gpib_str_state = 0;
					break;	
				case 0x93://08 00 02 AD 00														//查询SCPI等待时间
					t[0]= (GPIB_WAIT_TIME>>24)&0xFF;	
					t[1]= (GPIB_WAIT_TIME>>16)&0xFF;
					t[2]= (GPIB_WAIT_TIME>>8)&0xFF;
					t[3]= (GPIB_WAIT_TIME)&0xFF;
					return_care(bytes,t,4);
					gpib_str_state = 0;
					break;
				case 0x94:															//UART2数据转发			CARE_UART2:
					rt_device_write(rt_device_find("uart2"), 0, bytes+11, length-11);
					gpib_str_state = 0;
					break;	
				case 0x95:															//UART1数据转发			CARE_UART1:
					rt_device_write(rt_device_find("uart1"), 0, bytes+11, length-11);
					gpib_str_state = 0;
					break;	
				case 0x99://08 00 02 B1 00							//重启CARE			
					t[0] = 0x01;
					return_care(bytes,t,1);
				
					i = 100000;
					while(i--);
					NVIC_SystemReset();
					gpib_str_state = 0;
					break;	
			}
		}	
		protocol_state = 0;		
	}

	return 0;
}

rt_uint8_t GPIB_puts(rt_uint8_t str)
{
	rt_uint8_t count;
	rt_uint32_t put_str = 0;
	rt_uint8_t DIO[8]={25,19,21,23,26,18,20,22}; 										//LPC_GPIO3:DIO1,DIO5
	
	for(count=0; count<8; count++)
	{
		if ((str >> (count)) & 1)
		{
			put_str |= BV(DIO[count]);
		}		
	}		
	
	LPC_GPIO1->FIOCLR |= (put_str & (~(0x03<<25)));									//GPIB 高电平为"0"，低电平为"1"	
	LPC_GPIO3->FIOCLR |= (put_str & (~(0xFC<<17)));	
	return 0;
}

rt_uint8_t GPIB_gets(void)
{
	rt_uint32_t get_str=0;
	TE_LOW();		
	get_str =  ((PIN1_IS_CLR(DIO8)<<7)|\
							(PIN1_IS_CLR(DIO7)<<6)|\
							(PIN1_IS_CLR(DIO6)<<5)|\
							(PIN3_IS_CLR(DIO5)<<4)|\
							(PIN1_IS_CLR(DIO4)<<3)|\
							(PIN1_IS_CLR(DIO3)<<2)|\
							(PIN1_IS_CLR(DIO2)<<1)|\
							(PIN3_IS_CLR(DIO1)));
	return get_str;
}



rt_uint8_t gpib_cmd(char *bytes, rt_uint8_t length) 
{
    /* Write a GPIB command byte to the GPIB bus. This will assert the GPIB ATN line.*/
    return _gpib_write(bytes, length, 1, 0);
}

rt_uint8_t gpib_write(char *bytes, rt_uint8_t length, rt_bool_t use_eoi) 
{
    /* Write a GPIB data string to the GPIB bus. */
		return _gpib_write(bytes, length, 0, use_eoi);
}

rt_uint8_t _gpib_write(char *bytes, rt_uint8_t length, rt_bool_t cmd, rt_bool_t use_eoi)
{
	rt_uint32_t count;
	rt_uint8_t i;
	i = 0;
	tx_state = GPIB_TX_START;	
	if(cmd) { ATN_LOW();} else {ATN_HIGH();}		// Is it a command DC_LOW();	
	if(length==0) 															// If the length was unknown
	{
		length = strlen((char*)bytes); 						// Calculate the number of bytes to be sent 
	}
	while(tx_state != GPIB_TX_DONE)
	{
		switch(tx_state)
		{
			case GPIB_TX_START:						
				LPC_GPIO1->FIODIR  |=  BV(DIO2)|BV(DIO3)|BV(DIO4)|BV(DIO6)|BV(DIO7)|BV(DIO8);		
				LPC_GPIO3->FIODIR  |=  BV(DIO1)|BV(DIO5);
				EOI_HIGH();
				DAV_HIGH();			
				DC_LOW();	
				TE_HIGH();						//talk enable
				PE_LOW();
				tx_state = GPIB_TX_CHECK;
				break;
			case GPIB_TX_CHECK:
				LPC_GPIO1->FIOSET  |=  BV(DIO2)|BV(DIO3)|BV(DIO4)|BV(DIO6)|BV(DIO7)|BV(DIO8);		
				LPC_GPIO3->FIOSET  |=  BV(DIO1)|BV(DIO5);
// 				if(NRFD_IS_HIGH() && NDAC_IS_HIGH())			// If both NRFD and NDAC high, error
// 					tx_state = GPIB_TX_ERROR;															
// 				else			
					tx_state = GPIB_TX_PUT_DATA;					
				break;
			case GPIB_TX_PUT_DATA:
				if ((i == length-1) && (use_eoi))						// Assert EOI if on last byte and using EOI
				{
					EOI_LOW();					
				}
				GPIB_puts(bytes[i]);				
				++i;			
				count = WAIT;
				while(count--); 								// wait to settle line
				tx_state = GPIB_TX_WAIT_FOR_NRFD;
				GPIB_DELAY_COUNT = GPIB_WAIT_TIME;
				break;
			case GPIB_TX_WAIT_FOR_NRFD:								// Wait for NRFD high
				if (NRFD_IS_HIGH() || GPIB_DELAY_COUNT==0) tx_state = GPIB_TX_SET_DAV_LOW;
				break;
			case GPIB_TX_SET_DAV_LOW:
				DAV_LOW();															//DAV = 1; 
 				count = WAIT;
				while(count--); 									// wait to settle line
				tx_state = GPIB_TX_WAIT_FOR_NDAC;
				GPIB_DELAY_COUNT = GPIB_WAIT_TIME;
				break;
			case GPIB_TX_WAIT_FOR_NDAC:
				if (NDAC_IS_HIGH() || GPIB_DELAY_COUNT==0) tx_state = GPIB_TX_SET_DAV_HIGH;
				break;
			case GPIB_TX_SET_DAV_HIGH:	
				DAV_HIGH();				
				LPC_GPIO1->FIOSET  |=  BV(DIO2)|BV(DIO3)|BV(DIO4)|BV(DIO6)|BV(DIO7)|BV(DIO8);		
				LPC_GPIO3->FIOSET  |=  BV(DIO1)|BV(DIO5);			
			
				count = WAIT;
				while(count--); 									// wait to settle line
	
				if (i < length) 												// if More data
					tx_state = GPIB_TX_CHECK; 
				else 
					tx_state = GPIB_TX_DONE;				
				break;
			case GPIB_TX_ERROR:
				tx_state = GPIB_TX_DONE;				
				break;
			}
		}	
		if (cmd){ ATN_HIGH();}
		return 0;
}


rt_uint32_t gpib_read(rt_uint8_t use_eoi, rt_uint8_t eos_code, rt_uint8_t eot_enable, rt_uint8_t eot_char) 
{
	char byte;
	rt_uint8_t eoi_status = 1;
	rt_uint8_t eos_string[3];
	rt_uint8_t error_found = 0;
	rt_uint8_t i,char_counter = 0;   
	
	/* 接收线程的接收缓冲区*/ 
	char gpib_rx_buff[GPIB_MAX_RX_LEN];
	rt_uint8_t gpib_ptr=0;
	
	for (i=0;i<GPIB_MAX_RX_LEN-1;i++){gpib_rx_buff[i] = 0;}	
	

	// Setup the eos_string
	switch (eos_code) 
	{
	case 0:
		eos_string[0] = 13;
		eos_string[1] = 10;
		eos_string[2] = 0x00;
		break;
	case 1:
		eos_string[0] = 13;
		eos_string[1] = 0x00;
		break;
	case 2:
		eos_string[0] = 10;
		eos_string[1] = 0x00;
		break;
	default:
		eos_string[0] = 0x00;
		break;
	}
     
    // Beginning of GPIB read loop
    if(use_eoi) { // Read until EOI
        do {
            // First check for a read error
            if(gpib_read_byte(&byte, &eoi_status)){
							if(eot_enable) 
							{
								gpib_rx_buff[gpib_ptr++] = eot_char;
							}
							return 1;
            }
            // Check to see if the byte we just read is the specified EOS byte
            if(eos_code != 0) { // is not CR+LF terminated
                if((byte != eos_string[2]) || (eoi_status)) {								
 										gpib_rx_buff[gpib_ptr++] = byte; 
                    char_counter++;										
                }
            }  
						
						// Dual CR+LF terminated
						if (gpib_rx_buff[gpib_ptr-1] == 0x0A) eoi_status = 0;		
 
            // Check if ring is full, if so turn on TX interrupt
            if (char_counter-1 >= GPIB_MAX_RX_LEN) eoi_status = 0;
            
            // If this is the last character, turn on TX interrupt
            if(!eoi_status) {if(eot_enable) gpib_rx_buff[gpib_ptr++] = eot_char;}
        } while (eoi_status);
    // TODO: Flesh the rest of this reading method out
    /*} else if(read_until == 2) { // Read until specified character
    
    } else { // Read until EOS char found
    */
    }
    if(eot_enable) gpib_rx_buff[gpib_ptr++] = eot_char; 

 
//    if (1) { 	// FIXME: this should check what mode the adapter is in
//							// Command all talkers and listeners to stop
//        error_found = 0;
//        cmd_buf[0] = CMD_UNT;
//        error_found = error_found || gpib_cmd(cmd_buf, 1);
//        cmd_buf[0] = CMD_UNL;
//        error_found = error_found || gpib_cmd(cmd_buf, 1);
//    }
		
		if (Listen_Only_Mode){source_device = 5; memset(offline_filename, 0, 20);strcpy(offline_filename,"LISTEN.TXT");}
		return_care(gpib_rx_buff,gpib_rx_buff,gpib_ptr);
		
    return error_found;
}



rt_uint32_t gpib_read_byte(char *byte, rt_uint8_t *eoi_status)
{
//	rt_uint32_t count,count_time[2];
//	char cmd_buf[3];
	LPC_GPIO1->FIODIR  &=  ~(BV(DIO2)|BV(DIO3)|BV(DIO4)|BV(DIO6)|BV(DIO7));		
	LPC_GPIO3->FIODIR  &=  ~(BV(DIO1)|BV(DIO5));		
	rx_state = GPIB_RX_START;
	while(rx_state != GPIB_RX_DONE)
	{
		switch(rx_state)
		{
			case GPIB_RX_START:												
				NDAC_LOW();									// TE low,recevice.Assert NDAC, informing the talker we have not yet accepted the byte
				rx_state = GPIB_RX_ACCEPT;
				break;	
			case GPIB_RX_ACCEPT:
				NRFD_HIGH();			 					// Raise NRFD, informing the talker we are ready for the byte
				GPIB_DELAY_COUNT = GPIB_WAIT_TIME;						//1600ms
				rx_state = GPIB_RX_WAIT_DAV;
				break;	
			case GPIB_RX_WAIT_DAV:				// Wait here for DAV to go low
				if (!DAV_IS_HIGH()) rx_state = GPIB_RX_DAV_LOW; // Wait for DAV to go low, informing us the byte is read to be read
				if(GPIB_DELAY_COUNT == 0) rx_state = GPIB_RX_DAV_TIMEOUT;
				break;
			case GPIB_RX_DAV_LOW: //	
				GPIB_DELAY_COUNT = GPIB_WAIT_TIME;	
				NRFD_LOW();									// Set NRFD low ,Assert NRFD, informing the talker to not change the data lines
				*byte = GPIB_gets(); 				//Read the data on the port,  and read in the EOI line
				*eoi_status = EOI_IS_HIGH();
			
				NDAC_HIGH(); 								// Set NDAC high, informing talker that we have accepted the byte
				rx_state = GPIB_RX_WAIT_DAV_HIGH;
				break;	
			case GPIB_RX_WAIT_DAV_HIGH:		// Wait for DAV to go high; the talkers knows that we have read the byte
				if (DAV_IS_HIGH()) rx_state = GPIB_RX_DAV_HIGH;	
				if(GPIB_DELAY_COUNT == 0) rx_state = GPIB_RX_DAV_TIMEOUT;					
				break;	
			case GPIB_RX_DAV_HIGH:
				NDAC_LOW();									// Get ready for the next byte by asserting NDAC
				rx_state = GPIB_RX_FINISH;
				break;	
			case GPIB_RX_DAV_TIMEOUT:
//  				NRFD_LOW();
			
//        cmd_buf[0] = CMD_UNT;
//        gpib_cmd(cmd_buf, 1);
//        cmd_buf[0] = CMD_UNL;
//        gpib_cmd(cmd_buf, 1);
//				rx_state = GPIB_RX_DONE;			
				return 1;			
// 				break;
			case GPIB_RX_FINISH:
				rx_state = GPIB_RX_DONE;
				break;
		}
	} 
	return 0;
}


//
// Assert REN to put instrument in remote mode
// state = true -> assert REN, state = false -> deasert REN
//
void gpib_ren(rt_uint8_t state)
{
	if(state == true)
	{
		REN_LOW();
	}
	else
	{
		REN_HIGH();
	}
}


// Interface clear
void gpib_ifc(void)
{
//	rt_uint32_t count;	
	IFC_LOW();
	// Hold IFC low for >100us
	rt_thread_delay(1);
	IFC_HIGH();
	rt_thread_delay(1);
}

rt_uint8_t address_target_listen(rt_uint8_t address) 
{
	rt_uint8_t write_error = 0;
	char cmd_buf[4];
// 	cmd_buf[0] = CMD_UNT;

	cmd_buf[0] = CMD_UNL; // Everyone stop listening
	cmd_buf[1] = ((address&0x1F) | LISTEN);
	cmd_buf[2] = (care_address | TALK);
	cmd_buf[3] = 0x60;
	
	write_error = write_error || gpib_cmd(cmd_buf, 4);
	
	return write_error;
}


rt_uint8_t address_target_talk(rt_uint8_t address) 
{
	rt_uint8_t write_error = 0;
	char cmd_buf[4];
// 	cmd_buf[0] = CMD_UNT;
	
	cmd_buf[0] = CMD_UNL; // Everyone stop listening
	cmd_buf[1] = (care_address | LISTEN);
	cmd_buf[2] = ((address&0x1F) | TALK);
	cmd_buf[3] = 0x60;
	
	write_error = write_error || gpib_cmd(cmd_buf, 4);
	
	return write_error;
}


//send LF+EOI, UNL, UNT
rt_uint8_t send_gpib_unlisten(rt_uint8_t address) 
{
	rt_uint8_t write_error = 0;
	char cmd_buf[3];
// 	cmd_buf[0] = CMD_UNT;
	cmd_buf[0] = CMD_UNL; // Everyone stop listening
	write_error = write_error || gpib_cmd(cmd_buf, 1);
	return write_error;
}


//void serial_poll(rt_uint8_t address) 
//{
//	rt_uint8_t status_byte=0;
//	rt_uint8_t eoi_status=0;
//	rt_uint8_t i=0;
//	char cmd_buf[4];
//	
//	while (!care_protocol_state()){}
//	//if(protocol_state==0)
//	{
//	protocol_state = 1;
//	cmd_buf[0] = CMD_UNL; // Everyone stop listening
//	cmd_buf[1] = (care_address | LISTEN);
//	cmd_buf[2] = CMD_SPE;		
//	gpib_cmd(cmd_buf, 3);
//		

//	for(i=0;i<32;i++)
//	{
//		if(com_device[i][0])
//		{
//			cmd_buf[0] = (i | TALK);
//			gpib_cmd(cmd_buf, 1);
//			gpib_read_byte((char*)&status_byte,&eoi_status);
//			
//			
//			cmd_buf[0] = CMD_UNL; // Everyone stop listening
//			cmd_buf[1] = (i | LISTEN);
//			cmd_buf[2] = (care_address | TALK);
//			cmd_buf[3] = CMD_SPD; // disable serial poll
//			gpib_cmd(cmd_buf, 4);
//			rt_thread_delay(1);
//		}
//			
//		if(((status_byte&0x10) == 0x10)||(((status_byte&0x40) == 0x40)))
//		{
//			status_byte = 0;
////			current_gpib_address = i;
//			source_device = 0x80;
//			address_target_talk(i);												//put instrument in talk	
//			gpib_read(1,1,0,0);
//			rt_thread_delay(1);
//		}
//	}
//	}
//	protocol_state = 0;
//}




void return_care(char *source_bytes,char *bytes, rt_uint8_t length)
{		//08 16 07 B0 00 31 32 33 34 35
	rt_uint8_t i;
//	rt_uint16_t t1;
	
	if(bytes[length-1] == 0x0A)
	{
		if(bytes[length-2] != 0x0D) 
		{
			bytes[length-1] = 0x0D;
			bytes[length] 	= 0x0A;
			length = length+1;
		}
	}
	if(bytes[length-1] == 0x0D)
	{
		{
			bytes[length] 	= 0x0A;
			length = length+1;
		}
	}
	if((bytes[length-1] != 0x0D)&&(bytes[length-1] != 0x0A))
	{
		{
			bytes[length] 	  = 0x0D;
			bytes[length+1] 	= 0x0A;
			length = length+2;
		}
	}
	
	

	if (source_bytes[0] == 0x08)
	{
		for(i=length+4;i>=5;i--)
		{
			bytes[i]=bytes[i-5];
		}
		bytes[0] = source_bytes[0]+1;
		bytes[1] = 0;
		bytes[2] = 2+length;
		bytes[3] = source_bytes[3];
		bytes[4] = source_bytes[4];
		length = length+5;
	}
	else if((source_device&0x80) == 0x80)
	{
		for(i=length+4;i>=5;i--)
		{
			bytes[i]=bytes[i-5];
		}
		bytes[0] = 0x09;
		bytes[1] = gpib_address;
		bytes[2] = 2+length;
		bytes[3] = 0xAA;
		bytes[4] = 0x01;
		length = length+5;	
	}
	
	source_device = source_device&0xF;

	if((source_device) == 0) 
	{
		if(length > 1) rt_device_write(rt_device_find("uart0"), 0, bytes, length);//长度=1，0x00 不返回 2019-11-29 by ZDD
	}
	else if((source_device) == 1) 
	{
		if(length > 1) rt_device_write(rt_device_find("uart1"), 0, bytes, length);//长度=1，0x00 不返回 2019-11-29 by ZDD
	}
	else if((source_device) == 2) 
	{
//		rt_device_write(rt_device_find("uart2"), 0, bytes, length);
//		if(length > 1) {
//			//解决LABVIEW读取TCP时,只能判断结束符为CR（回车）加上LF（换行）或超时的问题(保证输出结尾为0D 0A)
//			if(bytes[length-2] != 0x0D && bytes[length-1] == 0x0A) { bytes[length-1] = 0x0D; bytes[length] = 0x0A; length = length + 1; }
		if(length > 1) 	GPIB_send(bytes, length);//长度=1，0x00 不返回 2019-11-29 by ZDD
//		}
	}	
	else if((source_device == 4)||(source_device == 5))
	{		
		
		memset(timestr,0,GPIB_MAX_RX_LEN+128);
		memset(tempstr,0,10);
				
		sprintf(tempstr,"%.2f  ",SENSOR_DATA[SENSOR_INDEX]);
				
		sprintf(timestr,"%04d/%02d/%02d %02d:%02d:%02d.%03d  ",
		(LPC_RTC->YEAR),
		(LPC_RTC->MONTH),
		(LPC_RTC->DOM),
		(LPC_RTC->HOUR),
		(LPC_RTC->MIN),
		(LPC_RTC->SEC),
		 ms_int);
		offline_writeln(strcat(timestr, strcat(tempstr, bytes)), length+strlen(timestr)+strlen(tempstr));
	}
}

/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
rt_int8_t readln(char *byte)
{
	int fd=0;	
	int count=1;
	char buf=0, i=0;	
	while ((buf!=0x0A)&&(buf!=';')&&(count != 0))
	{
		count = read(fd,&buf,1);
		byte[i++] = buf;
	}
	if (count==0)return 0; else return i;		
}


rt_int8_t offline_writeln(char *byte,rt_uint8_t len)
{
	int fd=0;	
	int count=1;
	char i=0;	//offline_filename
	if(len>0)
	{
		if (byte[len-1]!=0x0A){byte[len-1]=0x0D;byte[len]=0x0A;len+=1;}
		else if ((byte[len-1]==0x0A)&&(byte[len-2]!=0x0D)){byte[len-1]=0x0D;byte[len]=0x0A;len+=1;}
	}
	
	if (PIN0_IS_CLR(SD_INSERT)&&((offline_start)||(Listen_Only_Mode))) //插入TF写入数据
	{
		fd=open(offline_filename,DFS_O_CREAT|DFS_O_RDWR|DFS_O_APPEND,0); 	
		count = write(fd,byte,len); 	
		close(fd);
	}
	
	if(count>0)
	{
		rt_hw_led_on(0);			
		rt_device_write(rt_device_find("uart0"), 0, byte, len);	
		rt_device_write(rt_device_find("uart1"), 0, byte, len);	
		GPIB_send(byte, len);			
	}

	offline_return = 0;
	return i;		
}


void offline_collect(void)
{
	rt_uint8_t	i;
	char connchar;
	char CMD[64];
	
	for (i=0;i<MAX_OFFLINE_CMD;i++)
	{
		if (offline_str[i].period > 0) 
		{
				if (care_protocol_state()&&(!offline_return)) 
				{
					rt_thread_delay((rt_uint16_t)(offline_str[i].period));			
					memset(offline_filename, 0, 20);
					connchar = '/';//0x2F;
					strncpy(offline_filename,strcat(strcat(&connchar, offline_str[i].file_name),".txt") ,5+strlen(offline_str[i].file_name));
					strncpy(CMD,offline_str[i].cmd,strlen(offline_str[i].cmd));
					care_protocol(4,CMD,strlen(CMD));
				}	//GPIB	
			}	
	}	
}
